#include "cconfigurer.h"
#include "Plugins/initReader/SimpleIni.h"
#include "Plugins/dirHelper/cDirHelper.h"

namespace libcvos_vfr
{

	cConfigurer::cConfigurer():
		m_bInit(false)
	{

	}

	cConfigurer::~cConfigurer()
	{
		m_iniParser.Reset();
		m_bInit = false;
	}

	bool cConfigurer::loadIniFile(const char *fileName)
	{
		if (!Helper::Tool_CheckFileOrDirExsit(fileName))
		{
			fprintf(stderr, "file %s is not exsit.\n",fileName);
			return false;
		}

		SI_Error rc = m_iniParser.LoadFile(fileName);
		if (rc < 0)
		{ /* handle error */
			fprintf(stderr, "laod file %s failed.\n", fileName);
			return false;
		};
		m_strIniFile = fileName;

		m_bInit = true;
		return true;
	}

	void cConfigurer::createIniFile(const char *fileName)
	{
		std::string strNodeMap;
		strNodeMap.append("[default]\nkey = value\n");
		SI_Error rc = m_iniParser.LoadData(strNodeMap);
		if (rc < 0)
		{ /* handle error */
			fprintf(stderr, "LoadData failed.\n");
		};

		rc = m_iniParser.SaveFile(fileName);
		if (rc < 0)
		{ /* handle error */
			fprintf(stderr, "create IniFile %s failed.\n", fileName);
		};
	}

	std::string cConfigurer::get_section_value(const char *sectionName, const char *keyName)
	{
		if(!m_bInit)
		{
			fprintf(stderr, "please load ini file first.\n");
			return std::string("");
		}

		const char *pchValue = NULL;
		pchValue = m_iniParser.GetValue(sectionName, keyName, "0");

		return std::string(pchValue);
	}

	bool cConfigurer::set_section_value(const char *sectionName, const char *keyName, std::string value)
	{
		if(!m_bInit)
		{
			fprintf(stderr, "please load ini file first.\n");
			return false;
		}

		m_iniParser.SetValue(sectionName, keyName, value.c_str());
		SI_Error rc = m_iniParser.SaveFile(m_strIniFile.c_str());
		if (rc < 0)
		{
			/* handle error */
			fprintf(stderr, "save to  file failed.\n");
			return false;
		};
		m_iniParser.Reset();
		m_bInit = false;

		loadIniFile(m_strIniFile.c_str());
		return true;
	}

}
